package com.anosine.gpsl.android.ui.activity;

import java.util.ArrayList;
import java.util.List;
import com.anosine.gpsl.android.ui.activity.MoveHistoryBaiduMapActivity.MySpinnerAdapter;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.GPSLApp;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.WebConstants;
import com.anosine.gpsl.android.base.BaseActivity;
import com.anosine.gpsl.android.base.BaseAsyncTask;
import com.anosine.gpsl.android.base.ILoading;
import com.anosine.gpsl.android.entity.Login;
import com.anosine.gpsl.android.entity.MoveHistoryBean;
import com.anosine.gpsl.android.entity.MoveHistoryList;
import com.anosine.gpsl.android.ui.fragment.CommonHeaderFragment;
import com.anosine.gpsl.android.util.ButtonUtil;
import com.anosine.gpsl.android.util.HttpRequestListener;
import com.anosine.gpsl.android.util.MyLog;
import com.anosine.gpsl.android.util.SendHttpUtils;
import com.anosine.gpsl.android.util.StringUtil;
import com.anosine.gpsl.android.util.ToastHelper;
import com.anosine.gpsl.android.util.UserInfoProxy;
import com.anosine.gpsl.android.widget.wheelview.MyDateTimePickerDlg;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;


/**
 * @Title: MoveHistoryBaiduMapActivity
 * @Package com.anosine.gpsl.android.ui.activity
 * @Description: 我的界面
 * @author: sunny
 * @date: 2015-11-24
 * @version V1.0
 */
public class MoveHistoryBaiduMapActivity extends BaseActivity implements View.OnClickListener, OnGetGeoCoderResultListener {
	@ViewInject(R.id.mv_baidu_myposition)
	MapView mMvShow;
    BaiduMap mBmShow;
	@ViewInject(R.id.iv_show_map_type)
    ImageView mIvType;
	@ViewInject(R.id.et_time_input_start)
    EditText mEtStart;

    private boolean isFirstLoc = true;// 是否首次定位
    private boolean isShowDefaultMap=true;
	@ViewInject(R.id.content_tv_title)
    TextView title;
	/**
	 * @Title: BackOnClick(View v)
	 * @Description: 返回按钮的点击事件，点击关闭当前activity
	 * @param: View v
	 * @return: 无
	 * @throws
	 */
	@OnClick(R.id.button_left)
	private void BackOnClick(View v) {
		finish();
	}
    private BitmapDescriptor bdA ;
    private int mTargetIndex;
    private final List<LatLng> mListPosition=new ArrayList<LatLng>();
    private DataReSetTask mDataReSetTask;
    @ViewInject(R.id.btn_move_history_begin)
    Button mBtnStart;
    @ViewInject(R.id.tv_show_position_time)
    TextView mTvPositionTime;
    @ViewInject(R.id.tv_show_position_geo)
    TextView mTvPositionGeo;
    @ViewInject(R.id.btn_move_history_restart)
    Button mBtnReStart;
    @ViewInject(R.id.btn_begin_find)
    Button mBtnFind;
    @ViewInject(R.id.sp_SelectCar)
    Spinner SelectCar;
    String SelectOid;
    @Override
    protected void onBaseCreate(Bundle savedInstanceState) {
		SDKInitializer.initialize(this.getApplicationContext());    
		setContentView(R.layout.activity_movehistory);
		ViewUtils.inject(this); 
        title.setText("历史轨迹");   
        String [] m;
        m=new String[GPSLApp.mActive.size()];
        for(int i=0;i<GPSLApp.mActive.size();i++){
        	m[i]=GPSLApp.mActive.get(i).hn;
        }
    //  建立Adapter绑定数据源
        MySpinnerAdapter _MyAdapter=new MySpinnerAdapter(this, m);
        SelectCar.setAdapter(null);
		SelectCar.setAdapter(_MyAdapter);
		SelectCar.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				
				SelectOid=GPSLApp.mActive.get(position).oid;

			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});
        bdA=BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
        mBtnReStart.setOnClickListener(this);
        mBtnStart.setOnClickListener(this);

        mIvType.setOnClickListener(this);
        mEtStart.setOnClickListener(this);
        mBtnFind.setOnClickListener(this);
        // 地图初始化
        mBmShow = mMvShow.getMap();
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        isShowDefaultMap=true;
        showImageTypePic();
        showBaiduMapInfo();

    }
   
    public class MySpinnerAdapter extends BaseAdapter {
        private Context mContext;
        private String[] mList;
        public MySpinnerAdapter(Context pContext, String[]  pList) {
            this.mContext = pContext;
            this.mList = pList;
        }
      
        @Override
        public int getCount() {
            return mList.length;
        }
      
        @Override
        public Object getItem(int position) {
            return mList[position];
        }
      
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater _LayoutInflater=LayoutInflater.from(mContext);
            convertView=_LayoutInflater.inflate(R.layout.activity_familynumber_lv_item, null);
            if(convertView!=null) {
                TextView _TextView1=(TextView)convertView.findViewById(R.id.number);
                _TextView1.setText(mList[position]);
            }
            return convertView;
        }
    }
    private Handler mHandler=new Handler();

    private Runnable mRunnable=new Runnable() {
        @Override
        public void run() {
            int number=mListPosition!=null? mListPosition.size(): 0;
            mTargetIndex++;
            if (mTargetIndex>=number){
                mTargetIndex=0;
                mHandler.removeCallbacks(mRunnable);
                if (mBtnStart!=null){
                    mBtnStart.setText("播放");
                }
                if (mTvPositionTime!=null){
                    mTvPositionTime.setText("");
                }
            }else{
                mHandler.postDelayed(mRunnable, mMoveDelayRefreshUI);
                if (mBtnStart!=null){
                    mBtnStart.setText("暂停");
                }
                if (mTvPositionTime!=null){
                    String s=null;
                    if (mMoveHistoryList!=null&&mMoveHistoryList.list!=null){
                        try {
                            s=mMoveHistoryList.list.get(mTargetIndex).gpstime;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    mTvPositionTime.setText(s);
                }
            }
            showBaiduMapInfo();
        }
    };

    private void sendGetHistory(String start ){
        String url=String.format("%1s/%2s", AppConstants.sCommonUrl, WebConstants.Do_GetHistoryListOfPager_Action);
        showProgressInfo("请求中...");
        RequestParams params = new RequestParams();
        Login userInfo= UserInfoProxy.getInstance().getLoginInfo();
        params.addBodyParameter("rptquery.endtime", start+" 23:59:59");
        params.addBodyParameter("rptquery.starttime", start+" 00:00:01");
        params.addBodyParameter("rptquery.objectid", SelectOid);//userInfo!=null? userInfo.getObjectid(): ""
        params.addBodyParameter("rptquery.tracktype", "3");
        SendHttpUtils sendHttp=new SendHttpUtils();
        TypeToken type = new TypeToken<MoveHistoryList>() {
        };
        sendHttp.doRequest(url, params, type, new HttpRequestListener<MoveHistoryList>() {
            @Override
            public void onSuccess(String result, MoveHistoryList t) {
                dismissProgress();
                if (isFinishing()){
                    return;
                }
                mMoveHistoryList=t;
                int number=0;
                if (t!=null){
                    number=t.list!=null? t.list.size(): 0;
                    if (number>0){
                        mDataReSetTask=new DataReSetTask(MoveHistoryBaiduMapActivity.this, true );
                        mDataReSetTask.executeParallelly();
                    }
                }

                if (number<=0){
                    ToastHelper.toast("并无运动轨迹");
                }

            }

            @Override
            public void onFailure(String error) {
                dismissProgress();
                ToastHelper.toast(error);
            }
        });
    }


    private MoveHistoryList mMoveHistoryList;
    private GeoCoder mSearch = null;

    @Override
    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastHelper.toast("抱歉，未能找到结果");
            return;
        }
        if (mTvPositionGeo!=null){
            mTvPositionGeo.setText(result.getAddress());
        }

    }

    class DataReSetTask extends BaseAsyncTask<Void, Void, Void>{

        public DataReSetTask(ILoading loading, boolean showLoading) {
            super(loading, showLoading);

        }

        @Override
        protected Void onLoad(Void... params) throws Exception {
            int number=0;
            if (mMoveHistoryList!=null){
                number=mMoveHistoryList.list!=null? mMoveHistoryList.list.size(): 0;
                if (number>0){
                    mListPosition.clear();
                    for (MoveHistoryBean bean: mMoveHistoryList.list){
                        double lo= 0;
                        double lt= 0;
                        try {
                        	Log.i("TAG7",bean.lx+"/"+bean.ly);
                        	if(bean.lx==0&bean.ly==0){
                        		
                        	}else{
                            lo = (double)(bean.lo+bean.lx)/1000000.0f;
                            lt = (double)(bean.lt+bean.ly)/1000000.0f;
                            LatLng p1 = new LatLng(lt, lo);
                            mListPosition.add(p1);
                        	}
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                       
                    }

                }
            }
            return null;
        }

        @Override
        protected void onUI(Void aVoid) {
            int number=mListPosition!=null? mListPosition.size(): 0;
            if (number>0){
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(mListPosition.get(0));
                mBmShow.animateMapStatus(u);
                beginMoveHistory();
            }
        }
    }


    private void showBaiduMapInfo() {
        MyLog.i("xiaocai", "showBaiduMapInfo index="+mTargetIndex);
        mMvShow.getMap().clear();
        int number=mListPosition!=null? mListPosition.size(): 0;
        if (number>1){
            OverlayOptions ooPolyline = new PolylineOptions().width(5)
                    .color(0xAA00FF00).points(mListPosition);
            mBmShow.addOverlay(ooPolyline);
            OverlayOptions ooA = new MarkerOptions().position(mListPosition.get(mTargetIndex)).icon(bdA)
                    .zIndex(9).draggable(true);
            mBmShow.addOverlay(ooA);
        }

    }

    private void showImageTypePic() {
        if (isShowDefaultMap){
            mIvType.setImageResource(R.drawable.map_type_normal);
        }else{
            mIvType.setImageResource(R.drawable.map_type_satellite);
        }
    }


    @Override
    protected void initViews() {

    }

    @Override
    public void onClick(View view) {
        if (ButtonUtil.isFastDoubleClick()){
            return;
        }
        switch (view.getId()){
            case R.id.iv_show_map_type:
                isShowDefaultMap=!isShowDefaultMap;
                showImageTypePic();
                if (isShowDefaultMap){
                    mBmShow.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                }else{
                    mBmShow.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                }
                break;
            case R.id.btn_move_history_restart:
                beginMoveHistory();
                break;
            case R.id.btn_move_history_begin:
                if ("播放".equals(mBtnStart.getText().toString())){
                    mBtnStart.setText("暂停");
                    mHandler.postDelayed(mRunnable, mMoveDelayRefreshUI);
                    mTvPositionGeo.setText("");
                }else{
                    int number=mListPosition!=null? mListPosition.size(): 0;
                    if (number>0){
                        try {
                            LatLng ll=mListPosition.get(mTargetIndex);
                            // 反Geo搜索
                            mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                                    .location(ll));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    mHandler.removeCallbacks(mRunnable);
                    mBtnStart.setText("播放");
                }
                break;
            case R.id.btn_begin_find:
                String start=mEtStart.getText().toString();
                if (StringUtil.isEmptyOrNull(start)){
                    ToastHelper.toast("请输入开始时间");
                    return;
                }
                sendGetHistory(start);
                break;
            case R.id.et_time_input_start:
                MyDateTimePickerDlg.instance(false, false, 2000, 2016).show(getSupportFragmentManager(), null);
                MyDateTimePickerDlg.setmCallBack(
                        new MyDateTimePickerDlg.OnDateTimeSetListener() {
                            @Override
                            public void onDateTimeSet(int year, int monthOfYear, int dayOfMonth, int hour, int minute) {
                                //预约的时间不能超过当前时间
                                String time = String.format("%d-%02d-%d", year, monthOfYear, dayOfMonth, hour, minute);
                                mEtStart.setText(time);
                            }

                            @Override
                            public void onDateTimeCancel() {
                            }
                        }
                );
                break;
        }
    }

    @Override
    protected void onPause() {
        mMvShow.onPause();
        super.onPause();
        mHandler.removeCallbacks(mRunnable);
    }

    @Override
    protected void onResume() {
        mMvShow.onResume();
        super.onResume();
        beginMoveHistory();

    }

    private void beginMoveHistory() {
        mTargetIndex=0;
        mHandler.removeCallbacks(mRunnable);
        mHandler.postDelayed(mRunnable, mMoveDelayRefreshUI);
    }

    private int mMoveDelayRefreshUI=600;

    @Override
    protected void onDestroy() {
        if (mDataReSetTask!=null){
            mDataReSetTask.cancel(true);
        }
        // 关闭定位图层
        mBmShow.setMyLocationEnabled(false);
        mMvShow.onDestroy();
        mMvShow = null;
        if (mSearch!=null){
            mSearch.destroy();
        }
        super.onDestroy();
        bdA.recycle();
        mHandler.removeCallbacks(mRunnable);

    }


}
